package com.xiaoyu.izf.aspect;

import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.exception.BusinessException;
import com.xiaoyu.izf.model.exception.BusinessStatusEnum;
import com.xiaoyu.izf.service.UserInfoService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class RequestAspect {

    @Autowired
    private UserInfoService userInfoService;

    @Before("@annotation(RequestAuth)")
    public void before(JoinPoint joinPoint) {

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            UserInfo user = userInfoService.userInfoByToken(token);
            if(user!=null){
                return;
            }
        }
        throw new BusinessException(BusinessStatusEnum.NOT_LOGIN);
    }
}
